package com.example.fx.fg

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.base.entity.OrderDetail
import com.example.base.entity.PreOrderParamEntity
import com.example.base.mvvm.BaseFragment
import com.example.fx.R
import com.example.fx.adapter.CarAdapter
import com.example.fx.databinding.FragmentCarBinding
import com.example.fx.fgViewModel.CarViewModel

class CarFragment : BaseFragment<CarViewModel,FragmentCarBinding>() {
    lateinit var carAdapter: CarAdapter
    override fun getLayout(): Int  = R.layout.fragment_car

    override fun getViewModel(): Class<CarViewModel>  = CarViewModel::class.java

    override fun initView() {
        carAdapter = CarAdapter()
        binding.rvCar.adapter = carAdapter
        binding.rvCar.layoutManager = LinearLayoutManager(context)
        //请求购物车数据
        viewModel.getCar("true","1","20")

        //全选的点击事件
        binding.cb.setOnCheckedChangeListener { buttonView, isChecked ->
            binding.cb.setOnClickListener {
                carAdapter.data.forEach {
                    it.isChecked = isChecked
                }
                carAdapter.notifyDataSetChanged()
                totalAmount()//总金额也更新
            }
        }

        carAdapter.addChildClickViewIds(R.id.car_cb,R.id.tv_add,R.id.tv_sub)
        carAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.car_cb->{
                    //复选框
                    //更新data中的数据
                    carAdapter.data[position].isChecked = !carAdapter.data[position].isChecked
                }
                R.id.tv_add->{
                    //增加数量
                    //更新data中的数据
                    carAdapter.data[position].cartNum++
                    //页面上数据发生变化
                    (carAdapter.getViewByPosition(position,R.id.car_num) as TextView).text = "${carAdapter.data[position].cartNum}"
                    //调用后台
                    viewModel.updateCar(carAdapter.data[position].id,carAdapter.data[position].cartNum)
                }
                R.id.tv_sub->{
                    //减少数量
                    if(carAdapter.data[position].cartNum>1){
                        //更新data中的数据
                        carAdapter.data[position].cartNum--
                        //页面上数据发生变化
                        (carAdapter.getViewByPosition(position,R.id.car_num) as TextView).text = "${carAdapter.data[position].cartNum}"
                        //调用后台
                        viewModel.updateCar(carAdapter.data[position].id,carAdapter.data[position].cartNum)
                    }else{
                        //调用后台进行删除
                        val ids = ArrayList<Int>()
                        ids.add(carAdapter.data[position].id)
                        viewModel.deleteCar(ids)
                        //删除页面数据
                        carAdapter.data.removeAt(position)
                        //局部刷新
                        carAdapter.notifyItemRemoved(position)
                    }
                }
            }
            //计算金额
            totalAmount()
            //计算是否全选
            checkAll()
        }
        binding.createOrder.setOnClickListener {
            val flaglist = mutableListOf<Boolean>()
            carAdapter.data.forEach {
                flaglist.add(it.isChecked)
            }
            if(true in flaglist){
                //有结算商品，调用预下单接口
                val preOrderParamEntity = PreOrderParamEntity()
                val list = mutableListOf<OrderDetail>()
                carAdapter.data.forEach {
                    if(it.isChecked){//选中的，添加购物车id 到预下单的明细中
                        val orderDetail = OrderDetail()
                        orderDetail.shoppingCartId = it.id
                        list.add(orderDetail)
                    }
                }
                preOrderParamEntity.orderDetails = list
                preOrderParamEntity.preOrderType="shoppingCart"
                viewModel.preOrder(preOrderParamEntity)
            }else{
                ToastUtils.showLong("请至少选择一个商品进行结算")
            }
        }
    }

    private fun checkAll() {
        val flagList = mutableListOf<Boolean>()
        carAdapter.data.forEach {
            flagList.add(it.isChecked)
        }
        if(flagList.contains(false)){
            binding.cb.isChecked = false
        }else{
            binding.cb.isChecked = true
        }
    }

    private fun totalAmount() {
        var amount = 0f
        carAdapter.data.forEach {
            if(it.isChecked){
                amount+=it.cartNum*it.price.toFloat()
            }
        }
        binding.total.text = "合计:$amount 元"
    }

    override fun initData() {
        viewModel.getSuccess.observe(this){
            if(it.code==200){
                carAdapter.data.clear()
                carAdapter.data.addAll(it.data.list)
                carAdapter.notifyDataSetChanged()
            }
        }
        viewModel.addCarSuccess.observe(this){
            ToastUtils.showLong(it.message)
        }
        viewModel.updateSuccess.observe(this){
            ToastUtils.showLong(it.message)
        }
        viewModel.preOrderSuccess.observe(this){
            if(it.code==200){
                ARouter.getInstance().build("/app/OrderActivity").withString("preOrderNo",it.data.preOrderNo).navigation()
            }
        }
    }

}